import { BaseService, CoolCommException } from "@cool-midway/core";
import { CachingFactory, MidwayCache } from "@midwayjs/cache-manager";
import { Config, Init, Inject, InjectClient, Provide } from "@midwayjs/core";
import { PluginService } from "../../plugin/service/info";
import _ = require("lodash");


@Provide()
export class ProviderSmsService extends BaseService {
    @Config('module.provider.sms')
    config;

    @InjectClient(CachingFactory, 'default')
    midwayCache: MidwayCache;

    @Inject()
    pluginService: PluginService;

    plugin;

    @Init()
    async init() {
        for (const key of ['sms-tx', 'sms-ali']) {
            try {
                this.plugin = await this.pluginService.getInstance(key);
                if (this.plugin) {
                    this.config.pluginKey = key;
                    break;
                }
            } catch (e) {
                continue;
            }
        }
    }
    /**
      * 发送验证码
      * @param phone
      */
    async sendSms(phone) {
        // 随机四位验证码
        const code = _.random(1000, 9999);
        const pluginKey = this.config.pluginKey;
        // if (!this.plugin)
        //     throw new CoolCommException(
        //         '未配置短信插件，请到插件市场下载安装配置：https://cool-js.com/plugin?keyWord=短信'
        //     );
        try {
            if (pluginKey == 'sms-tx') {
                await this.plugin.send([phone], [code]);
            }
            if (pluginKey == 'sms-ali') {
                await this.plugin.send([phone], {
                    code,
                });
            }

            console.log(`验证码是：${code}`);
            this.midwayCache.set(`sms:${phone}`, code, this.config.timeout * 1000);
        } catch (error) {
            throw new CoolCommException('发送过于频繁，请稍后再试');
        }
    }

    /**
     * 验证验证码
     * @param phone
     * @param code
     * @returns
     */
    async checkCode(phone, code) {
        const cacheCode = await this.midwayCache.get(`sms:${phone}`);
        if (code && cacheCode == code) {
            return true;
        }
        return false;
    }

}